/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.service.cacheplugins  
 */
package com.apache.bid.service.cacheplugins;

import java.math.BigDecimal;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.api.vo.ResultMsg;
import com.apache.bid.common.BidCommonUtil;
import com.apache.bid.common.Constant;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.common.cache.BidDataBaseRunable;
import com.apache.bid.common.vo.BidItemCacheVo;
import com.apache.bid.entity.BidApply;
import com.apache.bid.entity.BidInfoJingjia;
import com.apache.bid.entity.BidItemPrice;
import com.apache.bid.entity.BidItemVip;
import com.apache.bid.manager.BidInfoJingjiaManager;
import com.apache.bid.service.cacheplugins.helper.ReductionPriceHelper;
import com.apache.cache.util.Validator;
import com.apache.tools.DateUtils;
import com.apache.uct.common.ToolsUtil;

/**
 * description:  竞价提交方法
 * @author Hou Dayu 创建时间：2016-3-28  
 * 
 */
public class JingjiaSavePluginImpl implements PluginConnector {

	private BidInfoJingjiaManager bidInfoJingjiaManager;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.zbxsoft.api.manager.PluginConnector#execute(com.zbxsoft.api.vo.ParamsVo)  
	 */
	@SuppressWarnings("rawtypes")
	public Object execute(ParamsVo param) throws Exception {
		String objId = String.valueOf(param.getParams("syncObjId"));
		Constant.getInstance().setJingjiaMap(objId, objId);
		final String key = Constant.getInstance().getJingjiaMap(objId);
		ResultEntity entity = new ResultEntity();
		BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("item");
		synchronized (key) {//加入同步锁
			String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmssSSS();
			String itemId = String.valueOf(param.getParams("itemId"));
			String userEname = String.valueOf(param.getParams("userEname"));
			String myPrice = String.valueOf(param.getParams("myPrice"));
			String itemStatus = String.valueOf(param.getParams("itemStatus"));
			param.setParams("bidTime", bidTime);
			BidItemCacheVo itemVo = (BidItemCacheVo) cache.getCacheObjectByKey(BidCacheManager.item_prefix + itemId);
			String applyKey = "";
			if (Constant.SETYPE_HD.equals(itemVo.getSessionType())) {
				applyKey = BidCacheManager.apply_prefix + userEname + "_" + itemId;
			} else {
				applyKey = BidCacheManager.apply_prefix + userEname + "_" + itemVo.getSessionId();
			}
			BidApply apply = (BidApply) cache.getCacheObjectByKey(applyKey);
			String vipKey = BidCacheManager.item_vip_prefix + userEname + "_" + itemId;

			BidItemPrice price = (BidItemPrice) cache.getCacheCloneByKey(BidCacheManager.item_price_prefix + itemId);
			BidItemVip vip = (BidItemVip) cache.getCacheObjectByKey(vipKey);
			String status = BidCommonUtil.getInstance().getStatus(price, bidTime);
			if (status.equals(itemStatus) && Constant.getInstance().getItemConfig("increase").equals(status)) {//加价期
				return addTimeItem(param, price, itemVo, apply, vip);
			}
			if (status.equals(itemStatus) && Constant.getInstance().getItemConfig("exercise").equals(status)) {//行权期
				return exerciseItem(param, price, itemVo, apply, vip);
			}
			ResultMsg msg = BidCommonUtil.getInstance().getCheckItem(status, myPrice, userEname, itemVo, price);
			if (!ToolsUtil.isEmpty(msg)) {
				entity.setResult("false");
				entity.setEntity("F".equals(msg.getFlag()) ? "false" : "true");
				entity.setMessage(msg.getMsg());
				return entity;
			}
			if (Constant.getInstance().getItemConfig("exercise").equals(status)
					|| Constant.getInstance().getItemConfig("increase").equals(status)) {
				entity.setResult("false");
				entity.setEntity("false");
				if (Constant.getInstance().getItemConfig("exercise").equals(status)) {
					entity.setMessage("标的不在行权期");
				} else {
					entity.setMessage("标的不在加价期");
				}
				return entity;
			}
			String colseTime = "";
			if (Constant.getInstance().getItemConfig("limitedOffer").equals(status)) {//限时报价期
				colseTime = setCloseTime(itemVo.getBidMode(), itemVo.getLimitTime(), bidTime);
			}
			if (!userEname.equals(price.getUserName())) {//判断购买数量
				boolean bailFlag = ReductionPriceHelper.getInstance().applyBuyItemNum(cache, itemVo, price, apply);
				if (!bailFlag) {
					entity.setResult("false");
					entity.setEntity("false");
					entity.setMessage("您已达到允许购买的标的数量");
					return entity;
				}
			}
			BigDecimal bidValue = new BigDecimal(0);
			boolean flag = false;
			BigDecimal myPrices = new BigDecimal(myPrice);
			if (Constant.BIDMODE_JTZX.equals(itemVo.getBidMode())) {//阶梯正向 
				if (!"0".equals(Validator.getDefaultStr(itemVo.getOncevalue(), "0"))) {///处理一口价,只有阶梯正向 
					BigDecimal onceValue = new BigDecimal(itemVo.getOncevalue());
					if (myPrices.compareTo(onceValue) >= 0) {
						bidValue = onceValue;
					} else {
						bidValue = myPrices;
					}
					flag = true;
				} else {
					bidValue = myPrices;
				}
			} else {
				bidValue = myPrices;
			}
			myPrice = String.valueOf(bidValue);
			BidInfoJingjia jingjia = new BidInfoJingjia();
			jingjia.setBidValue(myPrice);
			jingjia.setIncValue(String.valueOf(bidValue.subtract(new BigDecimal(price.getLastValue()))));
			jingjia.setAmount(String.valueOf(bidValue.multiply(new BigDecimal(itemVo.getItemNum()))));
			boolean mark = this.saveJingjiaInfo(param, price, itemVo, apply, vip, colseTime, jingjia, flag);
			if (mark) {
				entity.setResult("true");
				entity.setEntity("true");
				entity.setMessage("报价成功");
			} else {
				entity.setResult("false");
				entity.setEntity("false");
				entity.setMessage("报价失败");
			}
		}
		return entity;
	}

	/**
	 * description:  加价期
	 */
	private ResultEntity addTimeItem(ParamsVo param, BidItemPrice price, BidItemCacheVo itemVo, BidApply apply,
			BidItemVip vip) {
		ResultEntity entity = new ResultEntity();
		String userEname = String.valueOf(param.getParams("userEname"));
		String myPrice = String.valueOf(param.getParams("myPrice"));
		if (!userEname.equals(price.getUserName())) {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("您无权加价");
			return entity;
		}
		BigDecimal myPrices = new BigDecimal(myPrice);
		BigDecimal lastValue = new BigDecimal(price.getLastValue());
		if (myPrices.compareTo(lastValue) <= 0) {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("加价必须大于【" + myPrice + "】");
			return entity;
		}
		BidInfoJingjia jingjia = new BidInfoJingjia();
		jingjia.setBidValue(myPrice);
		jingjia.setIncValue(String.valueOf(myPrices.subtract(new BigDecimal(price.getLastValue()))));
		jingjia.setAmount(String.valueOf(myPrices.multiply(new BigDecimal(itemVo.getItemNum()))));
		price.setIfAddPrice("T");
		boolean mark = this.saveJingjiaInfo(param, price, itemVo, apply, vip, "", jingjia, false);
		if (mark) {
			entity.setResult("true");
			entity.setEntity("true");
			entity.setMessage("加价成功");
		} else {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("加价失败");
		}
		return entity;
	}

	/**
	 * description:  行权期
	 */
	private ResultEntity exerciseItem(ParamsVo param, BidItemPrice price, BidItemCacheVo itemVo, BidApply apply,
			BidItemVip vip) {
		ResultEntity entity = new ResultEntity();
		String myPrice = String.valueOf(param.getParams("myPrice"));
		if (!"e".equals(vip.getVipType())) {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("您无权行权");
			return entity;
		}
		if ("T".equals(price.getIfPrioFlag())) {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("行权已结束");
			return entity;
		}
		BidInfoJingjia jingjia = new BidInfoJingjia();
		jingjia.setBidValue(myPrice);
		jingjia.setIncValue("0.0");
		jingjia.setAmount(price.getAmount());
		jingjia.setBidId(Validator.generate());
		price.setIfPrioFlag("T");
		boolean mark = this.saveJingjiaInfo(param, price, itemVo, apply, vip, "", jingjia, false);
		if (mark) {
			entity.setResult("true");
			entity.setEntity("true");
			entity.setMessage("行权成功");
		} else {
			entity.setResult("false");
			entity.setEntity("false");
			entity.setMessage("行权失败");
		}
		return entity;
	}

	/**
	 * description:  添加报价记录
	 */
	private boolean saveJingjiaInfo(ParamsVo param, BidItemPrice price, BidItemCacheVo itemVo, BidApply apply,
			BidItemVip vip, String colseTime, BidInfoJingjia jingjia, boolean onceFlag) {
		boolean mark = false;
		String itemId = String.valueOf(param.getParams("itemId"));
		String userEname = String.valueOf(param.getParams("userEname"));
		String myPrice = String.valueOf(param.getParams("myPrice"));
		String bidTime = String.valueOf(param.getParams("bidTime"));
		String bidNum = String.valueOf(param.getParams("bidNum"));
		String userIp = String.valueOf(param.getParams("userIp"));
		jingjia.setBidTime(bidTime);
		//jingjia.setBidValue(myPrice);
		jingjia.setUserId(apply.getUserId());
		jingjia.setUserName(userEname);
		if (!Validator.isEmpty(vip))
			jingjia.setRightLevel(vip.getVipLevel());
		else
			jingjia.setRightLevel("0");
		jingjia.setItemId(itemId);
		jingjia.setUserIp(userIp);
		jingjia.setBidNum(Validator.getDefaultStr(bidNum, "0"));
		jingjia.setBidId(Validator.generate());
		mark = BidCacheFactory.getInstance().getCacheManager("jingjia").createCacheObject(jingjia);
		if (mark) {
			ParamsVo<BidInfoJingjia> vo = new ParamsVo<BidInfoJingjia>();
			vo.setObj(jingjia);
			BidDataBaseRunable runable = new BidDataBaseRunable(vo, "bidInfoJingjiaManager", "save");
			BidCacheFactory.getInstance().exeDatabase(runable);
			price.setAmount(jingjia.getAmount());
			price.setUserId(jingjia.getUserId());
			price.setLastRightLevel(jingjia.getRightLevel());
			price.setLastBidTime(bidTime);
			price.setLastValue(jingjia.getBidValue());
			price.setUserName(userEname);
			if (Validator.isNotNull(colseTime)) {
				price.setCloseTime(colseTime);
			}
			if (!"0".equals(Validator.getDefaultStr(itemVo.getOncevalue(), "0")) && onceFlag) {///处理一口价
				BigDecimal onceValue = new BigDecimal(itemVo.getOncevalue());
				BigDecimal myPrices = new BigDecimal(myPrice);
				if (myPrices.compareTo(onceValue) >= 0) {
					price.setFirstBidTime(bidTime);
					price.setCloseTime(bidTime);
				}
			}
			price.setBidNum(jingjia.getBidNum());
			price.setBidTimes(String.valueOf(Integer.parseInt(Validator.getDefaultStr(price.getBidTimes(), "0")) + 1));
			String itemStatus = String.valueOf(param.getParams("itemStatus"));
			if (Constant.getInstance().getItemConfig("exercise").equals(itemStatus)) {
				price.setIfPrioFlag("T");
			}
			BidCacheFactory.getInstance().getCacheManager("itemPrice").updateCacheObject(price);
			ParamsVo<BidItemPrice> priceVo = new ParamsVo<BidItemPrice>();
			priceVo.setObj(price);
			BidDataBaseRunable runable2 = new BidDataBaseRunable(priceVo, "bidItemPriceManager", "update");
			BidCacheFactory.getInstance().exeDatabase(runable2);
		}
		return mark;
	}

	/**
	 * description:  计算closeTime
	 */
	private String setCloseTime(String bidMode, String limitTimeStr, String bidTime) throws Exception {
		String colseTime = "";
		if (Constant.BIDMODE_JTZX.equals(bidMode) || Constant.BIDMODE_JTFX.equals(bidMode)) {
			colseTime = BidCommonUtil.getInstance().getMergeTime(bidTime, limitTimeStr);
		} else if (Constant.BIDMODE_FEJJZX.equals(bidMode) || Constant.BIDMODE_FEJJFX.equals(bidMode)) {
			colseTime = BidCommonUtil.getInstance().getMergeTime(bidTime, limitTimeStr);
		}
		return colseTime;
	}

	public void setBidInfoJingjiaManager(BidInfoJingjiaManager bidInfoJingjiaManager) {
		this.bidInfoJingjiaManager = bidInfoJingjiaManager;
	}

}
